package jpa;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

public class CreateHeaderHandler implements IRequestHandler {

	
	private String m_fileName;
	
	@Override
	public void handleRequest(HttpServletRequest request,
			HttpServletResponse response, IStatelessBean stateless,
			IStatefulBean stateful, ServletContext sc) throws ServletException,
			IOException {
		
		String name = null;
		String desc = null;
		try
		{
			name = getParameter("headerName", request.getParts());
			desc = getParameter("headerDescription", request.getParts());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		System.out.println(name);
		System.out.println(desc);

		String ID = Integer.toString(stateful.getCache().getCacheId());
		
		System.out.println(ID);
		
		//Must Create header before we can write a picture to it.
		stateless.addHeader(ID,name,desc);
		
		//gets the ID of the header for picture naming purposes.
		int id = stateless.getHeaderID(name);
		m_fileName = name+id;
		
		boolean hasPicture = doPic(request, response, sc);

		//call to edit with picture
		if(hasPicture)
		{
			//Adds the picture URL to the header with matching ID
			stateless.addPicToHeader(m_fileName, id);
		}
		
		RequestDispatcher rd = request.getRequestDispatcher("viewCache.jsp");
        rd.forward(request, response);

	}
	public String getParameter(String name, Collection<Part> parts) throws Exception
	{
	    String ret = null; 
		for (Part p : parts)
		{
		    for (String h : p.getHeaderNames())
		    {
		        String header = p.getHeader(h);
		        if (header.startsWith("form-data"))
		        {
		            String dataName = header.substring(header.indexOf('"')+1, header.lastIndexOf('"'));
		            if (dataName.equals(name))
		            {
		                BufferedReader reader = 
		                    new BufferedReader(new InputStreamReader(p.getInputStream(), "UTF-8"));
		                StringBuilder value = new StringBuilder();
		                char[] buffer = new char[1024];
		                for (int length = 0; (length = reader.read(buffer)) > 0;) {
		                    value.append(buffer, 0, length);
		                }
		                ret = value.toString();
		            }
		        }
		    }
		}
		return ret;
	}
	protected boolean doPic(HttpServletRequest request,
            HttpServletResponse response, ServletContext sc)
            throws ServletException, IOException 
    {
		System.out.println("1");
		boolean foundPic = false;
		
		
        response.setContentType("text/html;charset=UTF-8");

        String f = "C:\\Users\\MCLA\\images";
        File fFile = new File(f);
        String absoluteDiskPath = "";
        if(fFile.exists())
        {
        	absoluteDiskPath = f;
        }
        else
        {
        	String relativeWebPath = "/images/";
            absoluteDiskPath = sc.getRealPath(relativeWebPath);
            
        }
        
        final String path = absoluteDiskPath;
        
        //HAVING ISSUES WHEN NOT UPLOADING PIC
        //Ask mark about this in class
        Part filePart = request.getPart("file");

	       
        String extendString = filePart.toString();
	        
        System.out.println("EXTEND STRING: " + extendString);
        
        //Used to retrieve the file extension from the file (jpg, png, gif)
        String extension[] = extendString.split(",");
        extension = extension[0].split("\\.");
    
        if(extension.length >= 2)
        {
	        final String fileName = m_fileName+"."+extension[1];
	
	        System.out.println("fileName: "+fileName);
	        
	        OutputStream out = null;
	        InputStream filecontent = null;
	        final PrintWriter writer = response.getWriter();
	
	        try 
	        {
	            out = new FileOutputStream(new File(path + File.separator
	                    + fileName));
	            filecontent = filePart.getInputStream();
	
	            int read = 0;
	            final byte[] bytes = new byte[1024];
	
	            while ((read = filecontent.read(bytes)) != -1) 
	            {
	                out.write(bytes, 0, read);
	            }
	            writer.println("New file " + fileName + " created at " + path);
	        } 
	        catch (FileNotFoundException fne) 
	        {
	            writer.println("You either did not specify a file to upload or are "
	                    + "trying to upload a file to a protected or nonexistent "
	                    + "location.");
	            writer.println("<br/> ERROR: " + fne.getMessage());
	        } 
	        finally 
	        {
	            if (out != null) 
	            {
	                out.close();
	            }
	            if (filecontent != null) 
	            {
	                filecontent.close();
	            }
	            if (writer != null) 
	            {
	                writer.close();
	            }
	        }
        }
        
        return foundPic;
    }

}
